package com.sino.util;

import javax.servlet.http.HttpServletRequest;

public class CreatQueryCondition {
	private String condition = "";//查询参数

	private String hqlWhere = "";//查询条件
	//根据请求对象初始化condition和hqlWhere
	//condition查询参数，构造查询参数为了分页传递到下一页
	//hqlWhere查询条件，构造查询条件，用于查询满足条件的数据
	//用法：调用此方法传递一个请求对象，初始化上诉两个参数之后，即可以用getCondition（），getHqlWhere两个方法获得参数值
	public void initializtion(HttpServletRequest request) {
		StringBuffer bf = new StringBuffer();
		String paraName;
		java.util.Enumeration em = request.getParameterNames();
		while (em.hasMoreElements()) {
			paraName = em.nextElement().toString();
			// 获得查询参数
			
			if (request.getParameter(paraName) != null
					&& !(request.getParameter(paraName).equals(""))
					&& !(paraName.equals("page"))) {
				condition = condition + "&" + paraName + "="
						+ StringUtils.char2Gb2312(request.getParameter(paraName));
			}
			// 构造查询条件
			if (paraName.toLowerCase().startsWith("bm_")) {
				if (request.getParameter(paraName) != null
						&& !(request.getParameter(paraName).equals(""))) {
					if (paraName.endsWith("_begin_date")) {
						bf.append("TO_DAYS("+(paraName.substring(3, paraName.length() - 11)+")")
								+ " >= TO_DAYS('"
								+ request.getParameter(paraName)
								+ "') and ");
					} else if (paraName.endsWith("_end_date")) {
						bf.append("TO_DAYS("+(paraName.substring(3, paraName.length() - 9)+")")
								+ " <= TO_DAYS('"
								+ request.getParameter(paraName)
								+ "') and ");
					} else if (paraName.endsWith("_begin")) {
						bf.append(paraName.substring(3, paraName.length() - 6)
								+ " >= '" + request.getParameter(paraName)
								+ "' and ");
					} else if (paraName.endsWith("_end")) {
						bf.append(paraName.substring(3, paraName.length() - 4)
								+ " <= '" + request.getParameter(paraName)
								+ "' and ");
					} else {
						bf.append(paraName.substring(3, paraName.length())
								+ " like '%" + request.getParameter(paraName)
								+ "%' and ");
						/*
						 * } else { bf.append(paraName.substring(3,
						 * paraName.length()) + " = '" +
						 * request.getParameter(paraName) + "' and "); }
						 */
					}
				}
			}
			if (bf.length() > 4) {
				hqlWhere = (bf.toString()).replace('$', '.').substring(0,
						bf.length() - 4);
			} else {
				hqlWhere = (bf.toString()).replace('$', '.');
			}
		}
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public String getHqlWhere() {
		return hqlWhere;
	}

	public void setHqlWhere(String hqlWhere) {
		this.hqlWhere = hqlWhere;
	}
}
